﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using AutoMapper;

namespace TaskRecord.Web.Common
{
    /// <summary>
    /// this class come from Composable-https://github.com/ManpowerNordic/Composable.Monolithic.git
    /// by Magnus
    /// </summary>
    public class SafeConfiguration
    {
        private readonly IDictionary<Type, ISet<Type>> _mapping = new Dictionary<Type, ISet<Type>>();
        private readonly ConfigurationStore _configuration;

        public SafeConfiguration(ConfigurationStore configuration)
        {
            _configuration = configuration;
        }

        public IMappingExpression<TSource, TDestination> CreateMap<TSource, TDestination>()
        {
            InsertMappingHistoryOrThrowOnDuplicateMappings(typeof(TSource), typeof(TDestination));
            return _configuration.CreateMap<TSource, TDestination>();
        }

        public IMappingExpression CreateMap(Type sourceType, Type destinationType)
        {
            InsertMappingHistoryOrThrowOnDuplicateMappings(sourceType, destinationType);
            return _configuration.CreateMap(sourceType, destinationType);
        }

        private void InsertMappingHistoryOrThrowOnDuplicateMappings(Type sourceType, Type destinationType)
        {
            if (!_mapping.ContainsKey(sourceType))
            {
                _mapping[sourceType] = new HashSet<Type>();
            }

            if (_mapping[sourceType].Contains(destinationType))
            {
                throw new InvalidOperationException(String.Format("dumplicate mapper for {0} to {1}",sourceType.Name,destinationType.Name));
            }

            _mapping[sourceType].Add(destinationType);
        }
    }
}